package flc.ast.fragment;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import com.bigkoo.pickerview.utils.LunarCalendar;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import flc.ast.R;
import flc.ast.activity.AddCommemorateActivity;
import flc.ast.activity.AddCountdownActivity;
import flc.ast.adapter.CommemorateAdapter;
import flc.ast.adapter.CountdownAdapter;
import flc.ast.adapter.FestivalAdapter;
import flc.ast.bean.FestivalBean;
import flc.ast.bean.MyDayBean;
import flc.ast.databinding.FragmentHomeBinding;
import flc.ast.utils.*;
import flc.ast.utils.MyLunarCalendar;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.SPUtil;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends BaseNoModelFragment<FragmentHomeBinding> {

    private List<FestivalBean> listFestival = new ArrayList<>();
    private Dialog mySelFestivalDialog;
    private FestivalAdapter festivalAdapter;
    private int selPosition;
    private SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
    private int type = 0;
    private List<MyDayBean> listCommemorate = new ArrayList<>();
    private List<MyDayBean> listCountdown = new ArrayList<>();
    private CommemorateAdapter commemorateAdapter;
    private CountdownAdapter countdownAdapter;


    @Override
    protected int onCreate() {
        return R.layout.fragment_home;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(getActivity(), mDataBinding.event5Container);

        mDataBinding.tvFestivalSel.setOnClickListener(this);
        mDataBinding.tvCommemorateDay.setOnClickListener(this);
        mDataBinding.tvCountdownDay.setOnClickListener(this);
        mDataBinding.ivAdd.setOnClickListener(this);

        mDataBinding.rvCommemorateList.setLayoutManager(new LinearLayoutManager(mContext));
        mDataBinding.rvCommemorateList.setItemAnimator(new DefaultItemAnimator());
        commemorateAdapter = new CommemorateAdapter(mContext);
        mDataBinding.rvCommemorateList.setAdapter(commemorateAdapter);
        commemorateAdapter.setOnItemClickListener(new CommemorateAdapter.OnItemClickListener() {
            @Override
            public void onClick(MyDayBean bean, int position) {
                AddCommemorateActivity.myBean = listCommemorate.get(position);
                startActivity(AddCommemorateActivity.class);
            }

            @Override
            public void onClickDelete(MyDayBean bean, int position) {
                //保存数据
                List<MyDayBean> listSp = AppSpUtils.getCommemorateList();
                listSp.remove(position);
                AppSpUtils.savCommemorateList(listSp);
                getCommemorateData();
                ToastUtils.showShort(getString(R.string.delete_suc));
            }
        });

        mDataBinding.rvCountdownList.setLayoutManager(new LinearLayoutManager(mContext));
        mDataBinding.rvCountdownList.setItemAnimator(new DefaultItemAnimator());
        countdownAdapter = new CountdownAdapter(mContext);
        mDataBinding.rvCountdownList.setAdapter(countdownAdapter);
        countdownAdapter.setOnItemClickListener(new CountdownAdapter.OnItemClickListener() {
            @Override
            public void onClick(MyDayBean bean, int position) {
                AddCountdownActivity.myBean = listCountdown.get(position);
                startActivity(AddCountdownActivity.class);
            }

            @Override
            public void onClickDelete(MyDayBean bean, int position) {
                //保存数据
                List<MyDayBean> listSp = AppSpUtils.getCountdownList();
                listSp.remove(position);
                AppSpUtils.savCountdownList(listSp);
                getCountdownData();
                ToastUtils.showShort(getString(R.string.delete_suc));
            }
        });

        LunarCalendarUtils.LunarInfo lunarInfo = LunarCalendarUtils.INSTANCE.convertSolarToLunar(TimeUtils.getNowMills());
        mDataBinding.tvYear.setText(TimeUtils.getNowString(new SimpleDateFormat("yyyy年")));
        mDataBinding.tvGzsx.setText(lunarInfo.getGanZhiYear() + lunarInfo.getAnimal() + getString(R.string.unit_year));
        mDataBinding.tvDate.setText(TimeUtils.getNowString(new SimpleDateFormat("MM月dd日")));
        mDataBinding.tvWeek.setText(TimeUtils.getNowString(new SimpleDateFormat("EEEE")));
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.tvFestivalSel://节日选择
                mySelFestivalDialog.show();
                break;
            case R.id.tvCommemorateDay://纪念日
                type = 0;
                clearSelection();
                mDataBinding.tvCommemorateDay.setBackgroundResource(R.drawable.home_sel);
                mDataBinding.tvCommemorateDay.setTextColor(Color.parseColor("#585858"));
                getCommemorateData();
                break;
            case R.id.tvCountdownDay://倒计时
                type = 1;
                clearSelection();
                mDataBinding.tvCountdownDay.setBackgroundResource(R.drawable.home_sel);
                mDataBinding.tvCountdownDay.setTextColor(Color.parseColor("#585858"));
                getCountdownData();
                break;
            case R.id.ivAdd://添加
                if (type == 0) {
                    AddCommemorateActivity.myBean = null;
                    startActivity(AddCommemorateActivity.class);
                } else {
                    AddCountdownActivity.myBean = null;
                    startActivity(AddCountdownActivity.class);
                }
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        festivalAdapter.getItem(selPosition).setSelected(false);
        festivalAdapter.notifyItemChanged(selPosition);
        selPosition = position;
        festivalAdapter.getItem(selPosition).setSelected(true);
        festivalAdapter.notifyItemChanged(position);
        setData();
        mySelFestivalDialog.dismiss();
    }

    @Override
    protected void initData() {
        String[] strName = getContext().getResources().getStringArray(R.array.festival_name);
        String[] strDate = getContext().getResources().getStringArray(R.array.festival_date);
        for (int i = 0; i < strName.length; i++) {
            if (i == 0 || i == 2 || i == 3 || i == 8 || i == 10 || i == 11 || i == 15) {
//                listFestival.add(new FestivalBean(strName[i], strDate[i], true));
            } else {
                listFestival.add(new FestivalBean(strName[i], strDate[i], false));
            }
        }
        selPosition = SPUtil.getInt(mContext, Content.festivalPosition, 0);
        listFestival.get(selPosition).setSelected(true);

        festivalAdapter = new FestivalAdapter();
        festivalAdapter.setList(listFestival);
        setData();
        //选择节日弹框
        selFestivalDialog();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (type == 0) {
            getCommemorateData();
        } else {
            getCountdownData();
        }
    }

    private void setData() {
        mDataBinding.tvFestivalSel.setText(festivalAdapter.getItem(selPosition).getName());
        Date now = TimeUtils.getNowDate();
        try {
            Date festivalDate = format.parse(TimeUtils.getNowString(new SimpleDateFormat("yyyy")) + "." + festivalAdapter.getItem(selPosition).getDate());
            //毫秒ms
            long diff = festivalDate.getTime() - now.getTime();

            long diffDays = diff / (24 * 60 * 60 * 1000);
            long diffHours = diff / (60 * 60 * 1000) % 24;
            long diffMinutes = diff / (60 * 1000) % 60;
            long diffSeconds = diff / 1000 % 60;

            mDataBinding.tvFestivalInterval.setText(getString(R.string.festival_interval, diffDays, diffHours, diffMinutes, diffSeconds));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    private void getCommemorateData() {
        listCommemorate.clear();
        List<MyDayBean> listSp = AppSpUtils.getCommemorateList();
        if (listSp != null && listSp.size() > 0) {
            listCommemorate.addAll(listSp);
            commemorateAdapter.setmDatas(listCommemorate);
            mDataBinding.rvCommemorateList.setVisibility(View.VISIBLE);
            mDataBinding.rvCountdownList.setVisibility(View.GONE);
            mDataBinding.ivRecordNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvCommemorateList.setVisibility(View.GONE);
            mDataBinding.rvCountdownList.setVisibility(View.GONE);
            mDataBinding.ivRecordNoData.setVisibility(View.VISIBLE);
        }
    }

    private void getCountdownData() {
        listCountdown.clear();
        List<MyDayBean> listSp = AppSpUtils.getCountdownList();
        if (listSp != null && listSp.size() > 0) {
            listCountdown.addAll(listSp);
            countdownAdapter.setmDatas(listCountdown);
            mDataBinding.rvCommemorateList.setVisibility(View.GONE);
            mDataBinding.rvCountdownList.setVisibility(View.VISIBLE);
            mDataBinding.ivRecordNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvCommemorateList.setVisibility(View.GONE);
            mDataBinding.rvCountdownList.setVisibility(View.GONE);
            mDataBinding.ivRecordNoData.setVisibility(View.VISIBLE);
        }
    }

    //选择节日弹框
    private void selFestivalDialog() {
        mySelFestivalDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_sel_festival, null);
        mySelFestivalDialog.setContentView(inflate);
        mySelFestivalDialog.setCancelable(true);
        Window dialogWindow = mySelFestivalDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        RecyclerView recyclerView = inflate.findViewById(R.id.rvFestivalList);
        recyclerView.setLayoutManager(new GridLayoutManager(mContext, 5));
        recyclerView.setAdapter(festivalAdapter);
        festivalAdapter.setOnItemClickListener(this);
    }

    private void clearSelection() {
        mDataBinding.tvCommemorateDay.setBackgroundResource(0);
        mDataBinding.tvCommemorateDay.setTextColor(Color.parseColor("#91585858"));
        mDataBinding.tvCountdownDay.setBackgroundResource(0);
        mDataBinding.tvCountdownDay.setTextColor(Color.parseColor("#91585858"));
    }

}